package com.dream.myqiyi.ui;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Formatter;
import java.util.Locale;

import android.content.Context;
import android.media.MediaRecorder;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.SeekBar.OnSeekBarChangeListener;

import com.dream.myqiyi.BaseApp;
import com.dream.myqiyi.R;

public class RecorderPopup {
	private PopupWindow popupWindow;

	private MediaRecorder mediaRecorder;
	private File audioFile;
	private long start = 0;
	private long end = 0;
	
	private TextView recordTimeTv;
	private SeekBar recordSeekBar;
	private OnCloseListener closeListener = null;
	
	private Handler recordSeekBarHandler = new Handler();
	private Runnable refresh = new Runnable() {
		public void run() {
			int currently_Progress = recordSeekBar.getProgress() + 1000;	
			recordSeekBar.setProgress(currently_Progress);
			recordTimeTv.setText(getTime((new Date()).getTime() - start));
			recordSeekBarHandler.postDelayed(refresh, 1000);
		}
	};

	public RecorderPopup(Context context, String soundFile) {
		View view = LayoutInflater.from(context).inflate(R.layout.recorder_popup, null);
		popupWindow = new PopupWindow(view, LayoutParams.FILL_PARENT,  LayoutParams.WRAP_CONTENT);  
        //mPopupWindow.showAtLocation(findViewById(R.layout.note_view_activity), Gravity.LEFT|Gravity.TOP, 0, 0);  

		audioFile = new File(soundFile);

		Button btnStart = (Button) view.findViewById(R.id.btnStart);
		btnStart.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				mediaRecorder = new MediaRecorder();
				mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
				mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
				mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
				boolean success = false;
				try {
					success = audioFile.createNewFile();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					success = false;
				}
				if (success)
				{
					mediaRecorder.setOutputFile(audioFile.getAbsolutePath());
					try {
						mediaRecorder.prepare();
					} catch (IllegalStateException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					mediaRecorder.start();
					start = (new Date()).getTime();
					String msg = "正在录音...";	
					recordSeekBarHandler.postDelayed(refresh, 1000);
					BaseApp.showToast(msg);
				} else {
					BaseApp.showToast("创建录音文件失败！！！");
				}
					
			}
		});
		Button btnStop = (Button) view.findViewById(R.id.btnStop);
		btnStop.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (audioFile != null && mediaRecorder != null) {
					try {
						mediaRecorder.stop();
					} catch (IllegalStateException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					end = (new Date()).getTime();
					//length = end - start; 
					
					
					if (closeListener != null) {
						closeListener.onClose((int) (end - start));
					}
				}
				dismiss();
			}
		});
		recordTimeTv = (TextView) view.findViewById(R.id.record_time);
		recordSeekBar = (SeekBar) view.findViewById(R.id.record_seekBar);
		recordSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			@Override
			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {

			}

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
			}
		});
	}

	public void showAtLocation(View parent, int gravity, int x, int y) {
		popupWindow.showAtLocation(parent, gravity, x, y);

		// 使其聚集
		popupWindow.setFocusable(true);
		// 设置允许在外点击消失
		//popupWindow.setOutsideTouchable(true);
		// 刷新状态̬
		popupWindow.update();
	}

	// 隐藏菜单
	public void dismiss() {
		popupWindow.dismiss();
	}

	private String getTime(long timeMs) {
		long totalSeconds = timeMs / 1000;
		StringBuilder mFormatBuilder = new StringBuilder();
		@SuppressWarnings("resource")
		Formatter formatter = new Formatter(mFormatBuilder, Locale.getDefault());
		long seconds = totalSeconds % 60;
		long minutes = (totalSeconds / 60) % 60;
		long hours = totalSeconds / 3600;
		mFormatBuilder.setLength(0);

		if (hours > 0) {
			return formatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
		} else {
			return formatter.format("%02d:%02d", minutes, seconds).toString();
		}
	}
	
	// 设置菜单项点击监听器
	public void setOnCloseListener(OnCloseListener listener) {
		// this.listener = listener;
		closeListener = listener;
	}
	
	public interface OnCloseListener {
		public void onClose(int length);
	}

}
